<?php

namespace app\services;

use plugin\admin\app\model\TransferJob;
use plugin\admin\app\model\UserWork;
use plugin\admin\app\model\Work;
use support\JRTools;

class UserWorkService
{
    public static function hasBuy($userId, $workId)
    {
        $work = UserWork::where('user_id', $userId)->where('work_id', $workId)->where('is_pay', 1)->first();
        return !is_null($work);
    }

    public static function updateWorkInfo($id, $data)
    {
        $job = TransferJob::where('id', $id)->first();

        if (!$job) {
            throw new \Exception('未找到对应的任务.');
        }

        // 保存更新后的信息
        $job->after_edit_result = json_encode($data, JSON_UNESCAPED_UNICODE);
        $job->save();

        JRTools::transfer($job->id);

        return true;
    }

    public static function getEditLink($orderNo)
    {
        // Query the UserWork table for the record with the given order_no
        $userWork = UserWork::where('order_no', $orderNo)->first();

        if (!$userWork) {
            throw new \Exception('未找到对应的购买记录.');
        }

        // Decode the work_info field
        $work = Work::where('id', $userWork->new_work_id)->first();

        if (!$work) {
            $id = self::copy($orderNo);
            $userWork->new_work_id = $id;
            $userWork->save();
        } else {
            $id = $work->id;
        }

        return build_edit_tools_url('edit', $id);
    }

    public static function getAddLink()
    {
        return build_edit_tools_url('create');
    }

    public static function getPreviewLink($id)
    {
        return build_edit_tools_url('preview', $id);
    }

    public static function getList($page, $length, $isPay = null)
    {
        $offset = ($page - 1) * $length;

        // 构建查询
        $query = UserWork::select(['id', 'user_id', 'work_id', 'work_info', 'order_no', 'created_time', 'is_pay', 'price', 'new_work_id'])->where('user_id', get_user_id());
        if (!is_null($isPay)) {
            $query = $query->where('is_pay', $isPay);
        }

        // 获取总数
        $totalCount = (clone $query)->count();

        // 获取分页数据
        $list = $query->offset($offset)->limit($length)->orderBy('id', 'desc')->get()->toArray();

        // 循环处理 work_info 字段
        foreach ($list as $key => $item) {
            $work = json_decode($item['work_info'], true);

            $work['thumb'] = build_oss_url($work['thumb']);

            $images = json_decode($work['images'], true);

            foreach ($images as $key2 => $image) {
                $images[$key2] = build_oss_url($image);
            }
            $work['images'] = $images;

            $list[$key]['work_info'] = $work;
        }

        // 返回分页结果
        return [
            'total' => $totalCount,
            'page' => $page,
            'length' => $length,
            'data' => $list,
        ];
    }

    public static function copy($orderNo)
    {
        // Query the UserWork table for the record with the given order_no
        $userWork = UserWork::where('order_no', $orderNo)->first();

        if (!$userWork) {
            throw new \Exception('未找到对应的购买记录.');
        }

        // Decode the work_info field
        $workInfo = json_decode($userWork->work_info, true);

        if (!$workInfo) {
            throw new \Exception('作品信息解析失败.');
        }

        // Prepare the data for the new work
        $newWorkData = [
            'user_id' => $userWork['user_id'],
            'category_id' => $workInfo['category_id'] ?? null,
            'name' => $workInfo['name'] ?? null,
            'thumb' => $workInfo['thumb'] ?? null,
            'images' => $workInfo['images'] ?? null,
            'url' => $workInfo['url'] ?? null,
            'status' => $workInfo['status'] ?? null,
            'audit_time' => $workInfo['audit_time'] ?? null,
            'oss_name' => $workInfo['oss_name'] ?? null,
            'no' => $workInfo['no'] ?? null,
            'price' => $workInfo['price'] ?? null,
            'tags' => $workInfo['tags'] ?? null,
            'views' => 0,
            'sales' => 0,
            'is_public' => 0,
            'created_time' => date('Y-m-d H:i:s'),
            'is_buy' => 1
        ];

        // Insert the new work into the Work table
        $newWorkId = Work::insertGetId($newWorkData);

        if (!$newWorkId) {
            throw new \Exception('作品拷贝失败.');
        }

        return $newWorkId;
    }
}